package com.mgq.juc.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author MaGuangQi
 * 单线程池使用:
 * 1.适合任务按照顺序执行
 * 2.只有一个核心线程数,
 * 3.使用的无界队列
 * 4.当某个线程发生异常时,其他任务会创建一个新的线程继续执行
 * invokeAll()接收一个集合作为参数, 返回的是List<Future<Object>>对象
 * @date 2021-12-22 10:41
 **/
@Slf4j
public class TestSingleThreadPool {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        List<Future<String>> futures = executorService.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin 1");
                    Thread.sleep(2000);
                    return "1";

                },
                () -> {
                    log.debug("begin 2");
                    return "2";
                },
                () -> {
                    log.debug("begin 3");
                    return "3";
                }
        ));

        futures.forEach((future)-> {
            try {
                System.out.println(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
        Thread.sleep(1000);
        //shutdown 不会立即终止,而是等任务执行完成后停止
        executorService.shutdown();
    }
}
